package com.example.demo.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Map;

public class TorrentUtils {
    public static String calculateInfoHash(MultipartFile file) throws IOException {
        try {
            // 解码整个torrent文件
            Map<String, Object> torrentData = (Map<String, Object>) BencodeUtil.decode(file.getBytes());
            // 提取info字典
            Map<String, Object> info = (Map<String, Object>) torrentData.get("info");

            // 重新编码info字典
            byte[] encodedInfo = BencodeUtil.encode(info);

            // 计算SHA-1哈希
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] hash = md.digest(encodedInfo);

            return bytesToHex(hash);
        } catch (Exception e) {
            throw new IOException("Invalid torrent file", e);
        }
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}